<template>
  <div class="common-wrapper">
    <div class="common-search">
      <a-form layout="inline">
        <a-form-item label="部门">
          <a-tree-select
            v-model="search.department"
            style="width: 150px;"
            :dropdown-style="{ maxHeight: '400px',  overflow: 'auto' }"
            placeholder="请选择部门"
            allow-clear
            :tree-default-expand-all="false"
            :treeData="departmentList"
            :replaceFields="{children:'childs', title:'dep_name', key:'pkey', value: 'pkey' }"
          >
          </a-tree-select>
        </a-form-item>
        <a-form-item label="工种">
          <a-select v-model="search.work_type" mode="multiple" style="width:185px;">
            <a-select-option v-for="item in datadictionary" :key="item.data_value">
              {{ item.data_name }}
            </a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="员工姓名">
          <a-input v-model="search.name" style="width:100px;" />
        </a-form-item>
        <a-form-item label="员工工号">
          <a-input v-model="search.work_number" style="width:100px;"  />
        </a-form-item>
        <a-form-item label="时间范围">
          <a-range-picker @change="onChange" />
        </a-form-item>
      </a-form>
      <a-button type="primary" @click="getTableData(1)"> 搜索 </a-button>
      <a-button
        type="danger"
        style="background: #13c2c2; border-color: #13c2c2; margin-left: 20px"
        @click="openDialog()"
      >
        汇总考勤
      </a-button>
      <a-button  :loading="exportLoading" type="primary"
      style="background: #f39c12; border-color: #f39c12; margin-left: 20px"
      @click="onExport"> 导出 </a-button>
    </div>
    <div class="common-main" ref="main">
      <a-table
        size="middle"
        rowKey="card_number"
        :columns="columns"
        :scroll="{ y: 500 }"
        :data-source="dataSource"
        bordered
        :loading="tableLoading"
        :pagination="pagination"
        @change="handleTableChange"
      >
        <template slot="floatTime" slot-scope="text">
          <span>{{ text }}分钟</span>
        </template>
      </a-table>
    </div>
    <!-- modal -->
    <a-modal title="汇总考勤" :visible="visible" @cancel="handleCancel">
      <a-form-model ref="form" :model="form" :rules="rules">
        <a-form-model-item label="时间范围选择" :colon="false" prop="time">
          <a-range-picker v-model="form.time" :disabled-date="disabledDate" @change="onChangeRange" style="width: 100%;"/>
        </a-form-model-item>
      </a-form-model>
      <template slot="footer">
        <a-button @click="handleCancel">取消</a-button>
        <a-button type="primary" @click="submitStaff" :loading="subLoading">确定</a-button>
      </template>
    </a-modal>
  </div>
</template>

<script>
import { getPeriodTimeStatistical, process,getDailyStatisticalExport } from '@/api/attendance'
import { getDepartmentList, getDatadictionary } from '@/api/plan'
import * as XLSX from 'xlsx-js-style';
import moment from 'moment'
export default {
  data () {
    const columns = [
      {
        title: '部门',
        dataIndex: 'department',
        align: 'center'
      },
      {
        title: '工种',
        dataIndex: 'work_type_name',
        align: 'center'
      },
      {
        title: '姓名',
        dataIndex: 'name',
        align: 'center'
      },
      {
        title: '工号',
        dataIndex: 'card_number',
        align: 'center'
      },
      {
        title: '应出勤（天）',
        dataIndex: 'should_attendance_day',
        align: 'center'
      },
      {
        title: '实出勤（天）',
        dataIndex: 'real_attendance_day',
        align: 'center'
      },
      {
        title: '缺勤（天）',
        dataIndex: 'absenteeism_day',
        align: 'center'
      },
      {
        title: '应出勤（小时）',
        dataIndex: 'should_attendance_hour',
        align: 'center'
      },
      {
        title: '实出勤（小时）',
        dataIndex: 'real_attendance_hour',
        align: 'center'
      },
      {
        title: '缺勤（小时）',
        dataIndex: 'absenteeism_hour',
        align: 'center'
      },
      {
        title: '迟到次数',
        dataIndex: 'late_count',
        align: 'center'
      },
      {
        title: '早退次数',
        dataIndex: 'early_count',
        align: 'center'
      },
      {
        title: '缺卡次数',
        dataIndex: 'lack_count',
        align: 'center'
      }
    ]
    return {
      search: {
        name: '',
        work_number: '',
        department: '',
        work_type: [],
        start_time: '',
        end_time: '',
        page_index: 1,
        page_size: 20
      },
      columns,
      /* 分页参数 */
      pagination: {
        current: 1,
        pageSize: 20,
        showTotal: (total, range) => {
          return ' 共' + total + '条'
        },
        pageSizeOptions: ['10', '20', '30', '40', '50','100','500','1000'],
        showQuickJumper: true,
        showSizeChanger: true,
        total: 0
      },
      form: {
        time: null
      },
      loading: false,
      tableLoading: false,
      subLoading: false,
      visible: false,
      dataSource: [],
      rules: {
        time: [{ required: true, message: '请选择时间范围', trigger: 'change' }]
      },
      index: 0,
      datadictionary: [],
      departmentList: [],
      exportLoading: false
    }
  },
  mounted () {
    this.resize()
    this.getDepartmentList()
    this.getDatadictionary()
    window.addEventListener('resize', this.resize)
  },
  beforeDestroy () {
    window.removeEventListener('resize', this.resize)
  },
  methods: {
    disabledDate (current) {
      // 不可选未来时间
      return current && current > Date.now();
    },
    // 获取部门列表
    async getDepartmentList () {
      const { data } = await getDepartmentList()
      this.departmentList = data
      this.departmentList.unshift({
        dep_name: "全部",
        pkey: ''
      })
    },
    // 获取工种
    async getDatadictionary () {
      const { data } = await getDatadictionary({ data_type: 3 })
      this.datadictionary = data
    },
    openDialog () {
      this.visible = true
    },
    handleCancel () {
      this.visible = false
      this.$refs.form.resetFields();
    },
    onChangeRange (date, dateString) {
      this.form.time = dateString
    },
    submitStaff () {
      this.$refs.form.validate(async valid => {
        if (valid) {
          this.subLoading = true
          const params = {}
          params.start_date = this.form.time[0]
          params.end_date = this.form.time[1]
          const { succeeded } = await process(params);
          if (succeeded) {
            this.$message.success('操作成功！')
            this.visible = false
            this.$refs.form.resetFields();
          } else {
            this.$message.error('数据获取失败！')
          }
          this.subLoading = false
        } else {
          return false;
        }
      });
    },
    onChange (date, dateString) {
      this.search.start_time = dateString[0]
      this.search.end_time = dateString[1]
    },
    async resize () {
      // this.getpage_size()
      await this.getTableData()
    },
    // 获取表格
    async getTableData (cur) {
      this.tableLoading = true
      if (cur === 1) {
        this.search.page_index = cur
        this.pagination.current = cur
      } else {
        this.search.page_index = this.pagination.current
      }
      let work_types = this.search.work_type.join(',')
      const { data } = await getPeriodTimeStatistical({
        ...this.search,
        work_types
      })
      const { items, totalCount} = data
      this.dataSource = items
      this.pagination.total = totalCount
      this.tableLoading = false
    },
    getpage_size () {
      const height = this.$refs.main.offsetHeight - 68 - 30
      const page_size = Math.floor(height / 50)
      this.search.page_size = page_size
      this.pagination.page_size = page_size
    },
    handleTableChange (pagination, filters, sorter) {
      this.pagination = pagination
      this.search.page_size = pagination.pageSize
      this.getTableData()
    },
    async onExport() {
      this.exportLoading = true
      let work_types = this.search.work_type.join(',')
      const {data} = await getDailyStatisticalExport({
        ...this.search,
        work_types
      })
      this.exportLoading = false
      let listData = data
      const colsSize = 10 // 一行的列数量
      let tables = []
      let tablesStyle = [] // 样式
      let merges = [] // 合并单元格
      for (let i = 0; i < listData.length; i++) {
        let lists = listData[i].list
        let date = ''
        if(lists && lists.length > 0) {
            try {
              date = lists[0].date.substring(0,7)
            } catch (error) {
              
            }
        }
        // 头部
        tables.push([
          listData[i].work_type_name,
          '',
          '',
          listData[i].person_key,
          '',
          listData[i].name,
          '',
          date,
          '',
          '',
          ''
        ]
        )
        tablesStyle.push({
          bg: false,
          center: false,
          header: true
        })
        // 天数 - 最大一行10天
        let list = listData[i].list
        let chunkSize = colsSize
        let result = []
        // 转成块状
        for (let j = 0; j < list.length; j += chunkSize) {
          result.push(list.slice(j, j + chunkSize));
        }
        for (let j = 0; j < result.length; j++) {
          let dayArr = []
          let daily_shift_list = []
          let listStyle = []
          for (let k = 0; k < result[j].length; k++) {
            if(result[j][k].date && result[j][k].week) {
              dayArr.push(result[j][k].date.substring(8,10) + ' ' + result[j][k].week.substring(2,3))
            }else {
              dayArr.push('-')
            }
            let dailyList = result[j][k].daily_shift_list
            let dailyItem = []
            for (let g = 0; g < dailyList.length; g++) {
              let str = '-'
              let real_arrive = ''
              let real_back = ''
              if(dailyList[g].real_arrive) {
                real_arrive = dailyList[g].real_arrive.substring(11,19)
              }
              if(dailyList[g].real_back) {
                real_back = dailyList[g].real_back.substring(11,19)
              }
              if(real_arrive || real_back) {
                if(real_arrive) {
                  str = real_arrive + ' -'
                }
                if(real_back) {
                  str = '- ' + real_back
                }
                if(real_arrive && real_back) {
                  str = real_arrive + ' - ' + real_back
                }
              }
              dailyItem.push(str)
            }
            daily_shift_list.push(dailyItem.join('\n'))

            // status  0正常 1迟到：#C14444 2早退：#96808D 4旷工：#6D4C3A 8缺卡：#327875 其它: #ffff00
            let color = 'FFeeeeee'
            const str = String(result[j][k].daily_shift_list[0] ? result[j][k].daily_shift_list[0].status : '') 
            + String(result[j][k].daily_shift_list[1] ? result[j][k].daily_shift_list[1].status : '') 
            + String(result[j][k].daily_shift_list[2] ? result[j][k].daily_shift_list[2].status : '')
            if (str.indexOf('1') >= 0) {
              color = 'FFC14444'
            }else
            if (str.indexOf('2') >= 0) {
              color = 'FF96808D'
            }else
            if (str.indexOf('4') >= 0) {
              color = 'FF6D4C3A'
            }else
            if (str.indexOf('8') >= 0) {
              color = 'FF327875'
            }else
            if (str.indexOf('000') < 0) {
              color = 'FFffff00' 
            }
            if(result[j][k].daily_shift_list.length === 0) {
              color = 'FFffffff' 
            }
            listStyle.push({
              color: color
            })
          }
          // 时间
          tables.push(dayArr)
          tablesStyle.push({
            bg: false,
            center: true,
            header: false
          })
          // 阶段
          tables.push(daily_shift_list)
          tablesStyle.push({
            bg: true,
            center: true,
            header: false,
            listStyle
          })
        }
      }
      const workbook = XLSX.utils.book_new();
      const worksheet = XLSX.utils.json_to_sheet(tables,{
        skipHeader: true,
      });
      // 遍历所有行
      const rowCount = worksheet['!ref'].split(':')[1].match(/\d+/)[0];
      for (let i = 1; i <= rowCount; i++) {
        // 遍历所有列
        for (let col = 1; col <= colsSize; col++) {
          // 设置居中对齐样式
          const cellRef = XLSX.utils.encode_cell({c: col - 1, r: i - 1});
          if (!worksheet[cellRef]) worksheet[cellRef] = {};
          let s = {}
          if(tablesStyle[i-1].center) {
            s.alignment = { horizontal: 'center', vertical: 'center',wrapText: true }
          }else {
            s.alignment = { horizontal: 'left', vertical: 'center',wrapText: true }
          }
          if(tablesStyle[i-1].bg) {
            let bgColor = tablesStyle[i-1].listStyle[col-1]?.color ? tablesStyle[i-1].listStyle[col-1]?.color : "FFeeeeee"
            if(bgColor !== 'FFffffff') {
              s.fill = { fgColor: { rgb: bgColor }}
            }
          }
          if(tablesStyle[i-1].header) {
            merges.push({ s: { r: i-1, c: 0 }, e: { r: i-1, c: 2 } },{ s: { r: i-1, c: 3 }, e: { r: i-1, c: 4 } },{ s: { r: i-1, c: 5 }, e: { r: i-1, c: 6 } },{ s: { r: i-1, c: 7 }, e: { r: i-1, c: 9 } })
          }
          worksheet[cellRef].s = s;
        }
      }
      // 设置宽度
      let colsW = []
      for (let i = 0; i < colsSize; i++) {
        colsW.push({
          wpx: 130
        })
      }
      worksheet["!cols"] = colsW;
      // 合并单元格  最大10个单元格 头部比例3/2/6
      worksheet["!merges"] = merges;
      XLSX.utils.book_append_sheet(workbook, worksheet, "Sheet1");
      XLSX.writeFile(workbook, "考勤导出.xlsx");
    },
  }
}
</script>

<style lang="less">
.common-wrapper {
  height: 100%;
  padding: 20px;
}
.common-search {
  padding-bottom: 10px;
  display: flex;
  align-items: center;
  border-bottom: 1px solid #efefef;
}
.common-main {
  height: calc(100% - 50px);
  padding-top: 10px;
  .ant-table .ant-btn {
    height: 24px;
    line-height: 24px;
  }
}
</style>
